package org.todo.dao;

import java.util.List;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.todo.domain.Category;
import org.todo.domain.Todo;

/**
 * Implementation of CategoryDao interface
 * @author Matthias Braunhofer
 */
public class CategoryDaoImpl extends HibernateDaoSupport implements CategoryDao {
    private static final String BASE_CATEGORIES_QUERY = "from " + Category.class.getName() + " c ";
    private static final String USER_CATEGORIES_QUERY = BASE_CATEGORIES_QUERY + "where c.owner = ? or c.owner = 'Public' order by c.name";
    private static final String PUBLIC_CATEGORY_QUERY = BASE_CATEGORIES_QUERY + "where c.owner = 'Public'";
    private static final String CATEGORY_TODOS_QUERY = "from " + Todo.class.getName() + " t where t.category.id = ?";

    public List<Category> findCategoriesForUser(String username) {
       return getHibernateTemplate().find(USER_CATEGORIES_QUERY, username);
    }

    public void saveCategory(Category category) {
        getHibernateTemplate().saveOrUpdate(category);
        //in case of update make sure that its associated todo items are reindexed
        if (category.getId() > 0) {
            FullTextSession fts = Search.getFullTextSession(getSession());
            List<Todo> todos = getHibernateTemplate().find(CATEGORY_TODOS_QUERY, category.getId());
            for(Todo todo : todos) {
                fts.index(todo);
            }
        }
    }

    public void deleteCategory(Category category) {
        getHibernateTemplate().delete(category);
    }

    public Category getCategory(int categoryId) {
        return (Category)getHibernateTemplate().get(Category.class, categoryId);
    }

    public void createPublicCategory() {
        List categories = getHibernateTemplate().find(PUBLIC_CATEGORY_QUERY);
        if (categories.size() == 0) {
            Category category = new Category();
            category.setName("Public");
            category.setOwner("Public");
            saveCategory(category);
        }
    }
}
